import { useEffect, useState } from 'react';
import type { ChangeEvent } from 'react';
import type { Key } from 'react';
import { Button, Input } from 'antd';

import styles from './style.less';

const { TextArea } = Input;

type Props = {
  moduleTitle: string;
  ids: Key[];
  loading: boolean;
  onSearch: (ids: number[]) => void;
};

const Search: React.FC<Props> = ({ moduleTitle, ids, loading, onSearch }) => {
  const [albumIds, setAlbumIds] = useState<string>('');

  useEffect(() => {
    if (ids) {
      setAlbumIds(ids.join(','));
    }
  }, [ids]);

  const onChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
    setAlbumIds(e.target.value);
  };

  const search = () => {
    onSearch(albumIds.split(',').map(Number));
  };

  return (
    <div className={styles.search}>
      <div className={`${styles.albumId} formItemLabel`}>{moduleTitle}ID</div>
      <TextArea value={albumIds} onChange={onChange} />
      <Button
        type="primary"
        className={styles.searchBtn}
        loading={loading}
        onClick={search}
        disabled={albumIds === ''}
      >
        查询
      </Button>
    </div>
  );
};

export default Search;
